package com.ruoyi.web.controller.system;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.service.impl.SendSmsImpl;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Author 柳
 * @Date 2021/3/26
 * @Description TODO
 */
@RestController
@RequestMapping("/system/code")
public class SendController {
    @Autowired
    private SendSmsImpl sendSms;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @ApiOperation("发送短信验证码")
    @PostMapping("send/{phone}")
    public AjaxResult code(@PathVariable("phone") String phone){
        //调用发送方法 (模拟真实业务 redis)
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            //return  phone+":"+code+"已存在,还没有过期";
            return  AjaxResult.success(code);
        }
        //生成验证码并存储到redis中
        code= RandomStringUtils.random(4, "0123456789");
        //code= UUID.randomUUID().toString().substring(0,6);
        HashMap<String,Object> param=new HashMap<>();
        param.put("code",code);
        boolean isSend = sendSms.send(phone, "SMS_204277183", param);
        if (isSend){
            redisTemplate.opsForValue().set(phone,code,60, TimeUnit.SECONDS);
            //return  phone+":"+code+"发送成功！";
            return AjaxResult.success("操作成功！",code);
        }else{
            return  AjaxResult.error();
        }
    }

    @ApiOperation("短信验证码校验")
    @PostMapping("/verifyyzm")
    public AjaxResult verifyyzm(String phoneNum,String yzmCode){
        //判断验证码
        if(!yzmCode.equals(redisTemplate.opsForValue().get(phoneNum))||StringUtils.isBlank(phoneNum)||StringUtils.isBlank(yzmCode)){
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }





}
